import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { BannerEntity } from './banner.entity';
import { Repository } from 'typeorm';
import { TenantService } from '../tenant/tenant.service';
import { CommonStatus } from '~/common/entity/common.entity';
import { TenantEntity } from '../tenant/tenant.entity';
import { isNil } from 'lodash';
import { ErrorEnum } from '~/constants/error-code.constant';
import { CreateBannerDto } from './banner.dto';

@Injectable()
export class BannerService {
  constructor(
    @InjectRepository(BannerEntity)
    private readonly miniappBannerRepo: Repository<BannerEntity>,
    private readonly tenantService: TenantService
  ) {}

  async getAll(tenantId: number): Promise<BannerEntity[]> {
    // 按照时间倒序排
    return await this.miniappBannerRepo
      .createQueryBuilder('banner')
      .select(['banner.imageUrl', 'banner.linkUrl'])
      .innerJoin('banner.tenant', 'tenant')
      .where('banner.isActive = :isActive', { isActive: CommonStatus.YES })
      .andWhere('tenant.id = :tenantId', { tenantId })
      .orderBy('banner.createdAt', 'DESC')
      .getMany();
  }

  async create(dto: CreateBannerDto): Promise<BannerEntity> {
    const tenant: TenantEntity = await this.tenantService.getTenantById(dto.tenantId);

    if (isNil(tenant)) {
      throw new BadRequestException(ErrorEnum.NO_TENANT);
    }

    return this.miniappBannerRepo.save({ ...dto, tenant });
  }
}
